<?php
class LikesController extends AppController{
	
   public function isAuthorized($user) {
    // All registered users can add posts
      if ($this->action === 'likeOrUnlikePost') {
        return true;
      }

  // The owner of a post can edit and delete it

       return parent::isAuthorized($user);
    }
	
	
	public function likeOrNot($userid,$postid){
		if ($userid&&$postid) {
			$like = $this->Like->query('select * from Likes where user_id = '.$userid.' and post_id = '.$postid.'');
			if ($like) {
				return TRUE;
			}
			else {
				return FALSE;
			}
		}
		return false;
	}
	public function getLikeId($userid,$postid){
	    if ($userid&&$postid) {
			$like = $this->Like->query('select * from Likes where user_id = '.$userid.' and post_id = '.$postid.'');
            if ($like) {
            	
            	$likeid = $like[0]['Likes']['id'];
            	return $likeid;
            }
		}
		return NIL;
	}
	
	
	public function likeCount($postid){
	    if ($postid) {
			$likeCountresult = $this->Like->query('select count(id) from Likes where  post_id = '.$postid.'');
			$likeCountIn = $likeCountresult[0];
			$likeCount = $likeCountIn[0]['count(id)'];
			return $likeCount;
		}
	}
	
	public function likeOrUnlikePost(){
		if ($this->request->is('post')) {
		   $this->request->data['Like']['user_id'] = $this->Auth->user('id');
		   $likeOrNot = $this->likeOrNot( $this->request->data['Like']['user_id'],  $this->request->data['Like']['post_id']);
		   if ($likeOrNot){
		   	  $likedelete = $this->getLikeId($this->request->data['Like']['user_id'], $this->request->data['Like']['post_id']);
		   	  $this->Like->delete($likedelete);
		   }
		   else{
			  $this->Like->save($this->request->data);  
		   }
		$this->redirect(array('controller'=>'Posts','action'=>'view', $this->request->data['Like']['post_id']));
		}

	}
}